package com.flynn.rock.crm.service;

import cn.hutool.json.JSONUtil;
import com.flynn.rock.crm.entity.CrmConfigEntity;
import com.flynn.rock.crm.model.customer.request.AutoDispatchOrderRequest;
import com.flynn.rock.crm.model.customer.vo.AutoDispatchOrderVo;
import com.flynn.rock.crm.repository.CrmConfigRepository;
import com.flynn.rock.crm.schedule.CrmScheduled;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Optional;

@Service
public class CrmConfigService {

    private static final String AutoDispatchOrderConfigKey = "AutoDispatchOrderConfig";

    @Resource
    private CrmConfigRepository crmConfigRepository;

    @Resource
    private CrmScheduled crmScheduled;

    public AutoDispatchOrderVo getAutoDispatchOrderConfig() {
        return this.getAutoDispatchOrderConfigEntity()
                .map(config -> JSONUtil.parseObj(config.getConfigValue()).toBean(AutoDispatchOrderVo.class))
                .orElse(null);
    }

    public void editAutoDispatchOrderConfig(AutoDispatchOrderRequest request) {
        LocalDateTime now = LocalDateTime.now();
        CrmConfigEntity entity = new CrmConfigEntity();
        entity.setConfigKey(AutoDispatchOrderConfigKey);
        entity.setCreateTime(now);
        entity.setConfigValue(JSONUtil.toJsonStr(request));
        this.getAutoDispatchOrderConfigEntity().ifPresent(oldEntity -> {
            entity.setId(oldEntity.getId());
            entity.setCreateTime(oldEntity.getCreateTime());
        });
        entity.setUpdateTime(now);
        crmConfigRepository.save(entity);
        crmScheduled.clearEnableReceiveEmployeeCache();
    }

    private Optional<CrmConfigEntity> getAutoDispatchOrderConfigEntity() {
        CrmConfigEntity entity = new CrmConfigEntity();
        entity.setConfigKey(AutoDispatchOrderConfigKey);
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("configKey", ExampleMatcher.GenericPropertyMatcher::contains);
        Example<CrmConfigEntity> example = Example.of(entity, matcher);
        return crmConfigRepository.findOne(example);
    }
}
